package zb.WX.service.web;

import com.google.gson.Gson;
import org.springframework.stereotype.Service;
import zb.WX.bean.web.AuthorizedParam;
import zb.WX.bean.web.UserInfo;
import zb.WX.util.GlobalVar;
import zb.WX.util.HttpsUtil;

import javax.servlet.http.HttpSession;


/**
 * 1.用户授权后用code换取页面access_token
 * 2.刷新access_token(如果需要)
 * 3.拉取用户信息
 * 注意：
 * 1).code作为换取access_token的票据，每次用户授权带上的code将不一样，code只能使用一次，5分钟未被使用自动过期。
 * 2)页面access_token有效期为7200秒，refresh_token有效期为30天，可以用 refresh_token刷新access_token
 * 3)30天以后需用户重新授权才能再次拉取用户信息
 *
 * @author Administrator
 */
@Service
public class TargetService {

    /*
     * 拉取用户信息
     */
    public UserInfo getUserInfo(String code) {
        AuthorizedParam authorizedParam = getAuthorizedParam(code);
        String urlStr = GlobalVar.USER_INFO_WEB.replace("ACCESS_TOKEN", authorizedParam.getAccess_token()).replace("OPENID", authorizedParam.getOpenid());
        String result = HttpsUtil.getHttpsToJson(urlStr, null);
        System.out.println("拉取到的用户信息：" + result);
        Gson gson = new Gson();
        UserInfo userInfo = gson.fromJson(result, new UserInfo().getClass());
        return userInfo;
    }


    /*
     * code换取获取网页信息如下：
     * access_token，expires_in，refresh_token，openid，scope
     */
    public AuthorizedParam getAuthorizedParam(String code) {
        String urlStr = GlobalVar.ACCESS_TOKEN_WEB.replace("APPID", GlobalVar.APPID).replace("SECRET", GlobalVar.APPSECRET).replace("CODE", code);
        String result = HttpsUtil.getHttpsToJson(urlStr, null);
        Gson gson = new Gson();
        AuthorizedParam authorizedParam = gson.fromJson(result, AuthorizedParam.class);
        return authorizedParam;
    }

    /*
     * 当access_token过期时，可用于刷新access_token：
     * 1.session中获取refresh_token
     *
     */
    public AuthorizedParam refreshToken(String appid, HttpSession session) {

        AuthorizedParam ap = (AuthorizedParam) session.getAttribute("authorizedParam");

        String urlStr = GlobalVar.REFRESH_ACCESS_TOKEN.replace("APPID", appid).replace("REFRESH_TOKEN", ap.getRefresh_token());

        String result = HttpsUtil.getHttpsToJson(urlStr, null);

        Gson gson = new Gson();

        AuthorizedParam apobj = gson.fromJson(result, AuthorizedParam.class);

        return apobj;
    }
}
